﻿using System;
using System.Threading.Tasks;
using BookSleeve;
using RedisDemos.Extensions;

namespace RedisDemos.Scenarios
{
    public class UserAgents : Scenario
    {
        protected override async Task Perform(RedisConnection conn)
        {
            await Task.WhenAll(UserVisit(conn, "Firefox", "Windows XP", "127.0.0.1"),
                               UserVisit(conn, "MSIE", "Windows 7", "127.0.0.2"),
                               UserVisit(conn, "MSIE", "Windows 7", "127.0.0.2"),
                               UserVisit(conn, "Chrome", "Ubuntu", "127.0.0.3"),
                               UserVisit(conn, "Firefox", "Ubuntu", "127.0.0.4"),
                               UserVisit(conn, "Firefox", "Ubuntu", "127.0.0.4"),
                               UserVisit(conn, "Chrome", "Ubuntu", "127.0.0.4"),
                               UserVisit(conn, "MSIE", "Windows 7", "127.0.0.5"),
                               UserVisit(conn, "Safari", "OS X", "127.0.0.6"),
                               UserVisit(conn, "MSIE", "Windows 8", "127.0.0.7"));

            await TopBrowser(conn, "browser", "Safari");
            await TopBrowser(conn, "os", "Windows 7");
            await TopBrowser(conn, "ip", "127.0.0.4");
        }

        private async Task UserVisit(RedisConnection conn, String browser, String os, String ip)
        {
            //ZINCRBY key increment member
            await Task.WhenAll(conn.SortedSets.Increment(Db, "visits:browser", browser, 1),
                               conn.SortedSets.Increment(Db, "visits:os", os, 1),
                               conn.SortedSets.Increment(Db, "visits:ip", ip, 1));
        }

        private async Task TopBrowser(RedisConnection conn, String type, String what)
        {
            "*** {0}".LogInfo(type.ToUpperInvariant());

            //ZREVRANK key member
            var result = await conn.SortedSets.Rank(Db, "visits:" + type, what, ascending: false);
            "{0} are no. {1}".LogInfo(what, result + 1);

            //ZREVRANGE keys tart stop [WITHSCORES]
            var topThree = await conn.SortedSets.Range(Db, "visits:" + type, 0, 2, ascending: false);

            "Top3:".LogInfo();
            topThree.For((i, b) => "{0}) {1} - {2}".LogInfo(i + 1, b.Key.AsString(), b.Value));
        }
    }
}
